#!/usr/bin/env node

const https = require('https'),
      url  = require('url'),
      fs   = require('fs'),
      http = require('http'),
      cheerio = require('cheerio'),
      addr = 'https://trade.maoyan.com/films?showType=3';

let opt = url.parse(addr);
opt.headers = {
  'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36',
};

var arr = [];
https.get(opt,(res) => {
  let data = '';

  res.on('data',(chunk) => data += chunk);
  res.on('end',() => {
    let $ = cheerio.load(data);
    let title = $('body').find('div.movie-item-title');
    let movieId = $('body').find('div.movie-item-title>a');
    let range = $('body').find('div.channel-detail-orange');

    
    for(let i = 0; i < title.length; i++){
      arr[i] = {
        movieId:$(movieId[i]).attr('href').split('/')[2],
        movieName:$(title[i]).attr('title'),
        movieRange:$(range[i]).text().trim()
      };
    }
  });
});

let html = fs.readFileSync('./index.html').toString('utf8');
//arr = JSON.stringify(arr);
//console.log(arr);
http.createServer((req,res) => {
  let ads = url.parse(req.url);
  if(ads.pathname === '/getlist'){
    res.writeHead(200,{
      'Content-type':'application/json'
    }); 
    
    let a = JSON.stringify(arr);
    res.end(a);
  }
  res.end(html);
}).listen(8080);
